﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using MySql.Data.MySqlClient;
using Models;

namespace DAL
{
    public class GiveClanService
    {
        /// <summary>
        /// 根据血盟名称，查出血盟名称ID,目前没用到
        /// </summary>
        /// <param name="clanName">血盟名称</param>
        /// <returns></returns>
        private string GetClanIDBYClanName(string clanName)
        {
            string clanID = string.Empty;
            try
            {
                string sql = string.Format("select clan_id from clan_data where clan_name={0} ", clanName);
                MySqlCommand com = new MySqlCommand(sql, DBHelper.con);
                DBHelper.con.Open();
                clanID = com.ExecuteScalar().ToString();
            }
            catch
            {
                Error.s = "读取数据库时发生错误！";
            }
            finally
            {
                DBHelper.con.Close();
                DBHelper.con.Dispose();
            }
            return clanID;
        }


        private string GetLoginIDBYCharID(string charID)
        {
            string LoginID = string.Empty;
            try
            {
                string sql = string.Format("select account_name from characters where objid={0} ", charID);
                MySqlCommand com = new MySqlCommand(sql, DBHelper.con);
                DBHelper.con.Open();
                LoginID = com.ExecuteScalar().ToString();
            }
            catch
            {
                Error.s = "读取数据库时发生错误！";
            }
            finally
            {
                DBHelper.con.Close();
                DBHelper.con.Dispose();
            }
            return LoginID;
        }

        /// <summary>
        /// 根据血盟ID，查出血盟成员帐号到List
        /// </summary>
        /// <param name="clanName">血盟名称</param>
        /// <returns></returns>
        private List<string> GetAccNameBYClanID(int clanID, int level, int type)
        {
            List<string> accID = new List<string>();
            try
            {
                string sql = string.Empty;
                switch(type)
                {
                    case 1:
                        sql = string.Format("select account_name from characters where ClanID='{0}' and level >={1}", clanID, level);
                        break;
                    case 2:
                        sql = string.Format("select leader_id from clan_data where hascastle={0}", clanID);//查出统治城堡的王族ID
                        break;
                    case 3:
                        sql = string.Format("select account_name from characters where charname='{0}' and level >={1}", clanID, level);
                        break;
                }
                MySqlCommand com = new MySqlCommand(sql, DBHelper.con);
                DBHelper.con.Open();
                MySqlDataReader reader = com.ExecuteReader();
                
                while (reader.Read())
                {
                    switch (type)
                    {
                        case 1:
                            accID.Add(reader["account_name"].ToString());
                            break;
                        case 2:
                            accID.Add(reader["leader_id"].ToString());
                            break;
                    }
                }
                reader.Close();
            }
            catch
            {
                Error.s = "读取数据库时发生错误！";
            }
            finally
            {
                DBHelper.con.Close();
                DBHelper.con.Dispose();
            }
            //未注册限制
            if (accID.Count > Config.maxCountByGiveClan && Register.isReg == false)
            {
                accID.Clear();
            }
            return accID;
        }

        /// <summary>
        /// 根据获取到的角色ID 循环添加指定道具
        /// </summary>
        /// <param name="clanID">血盟ID</param>
        /// <param name="itemID">道具ID</param>
        /// <param name="count">道具数量</param>
        /// <param name="level">等级</param>
        /// <param name="type">物品类型</param>
        /// <returns></returns>
        public string AddItemBYCharID(int clanID,int itemID, int count, int level, int addType)
        {
            List<string> accID = GetAccNameBYClanID(clanID, level, addType);
            if (accID.Count < 1)
            {
                return "没有可赠送的成员";
            }
            int a = 0;//成功
            int b = 0;//失败
            int itemType = ItemType(itemID);
            for (int y = 0; y < accID.Count; y++)//循环增加
            {
                int type = 1;
                int wtype=0;
                if (warehouseType(itemID, accID[y]) > 1)
                {
                    wtype = 1;
                }
                if (itemType + wtype == 2)//道具可重叠,且仓库中有该道具
                {
                    type = 2;//发送道具时只修改该道具的数量,而不是增加
                }
                string LoginID = string.Empty;
                if (addType == 2)
                {
                    type = 3;//为拥有城堡的王子赠送
                    LoginID = GetLoginIDBYCharID(accID[y]);
                }
                
                int isok = 0;
                int id = ItemMaxId.ID();//玩家道具的流水号
                //int id = 100000000;//固定的流水号
                try
                {
                    string sql = string.Empty;
                    if (AddPay(id, accID[y], itemID, count,type))//记录成功后赠送
                    {
                        switch (type)
                        {
                            case 1://插入新道具
                                sql = string.Format("insert into character_warehouse(id,account_name,item_id,item_name,count) values({0},'{1}',{2},'LinSM赠送',{3})", id + 1, accID[y], itemID, count);//赠送道具                            
                                break;
                            case 2://修改道具数量
                                sql = string.Format("update character_warehouse set count=count+{0} where item_id={1} and account_name='{2}' order by item_id desc Limit 1", count, itemID, accID[y]);
                                break;
                            case 3://为拥有城堡的王族赠送
                                for (int i = 1; i <= 4; i++)
                                {
                                    DeleteCastleItem(itemID, i);
                                }
                                sql = string.Format("insert into character_warehouse(id,account_name,item_id,item_name,count) values({0},'{1}',{2},'LinSM赠送',{3})", id + 1, LoginID, itemID, count);//赠送道具
                                break;
                        }
                    }
                    MySqlCommand com = new MySqlCommand(sql, DBHelper.con);
                    DBHelper.con.Open();
                    isok = Convert.ToInt32(com.ExecuteNonQuery());
                }
                catch
                {
                    Error.s = "读取数据库时发生错误！";
                }
                finally
                {
                    DBHelper.con.Close();
                    DBHelper.con.Dispose();
                }
                if (isok > 0)
                {
                    a++;
                    id++;
                }
                else
                {
                    b++;
                }
            }
            return "赠送成功" + a + "条\n赠送失败" + b + "条";
        }

        /// <summary>
        /// 记录赠送的道具
        /// </summary>
        /// <param name="accName">账号</param>
        /// <param name="itemID">道具</param>
        /// <param name="count">数量</param>
        /// <returns></returns>
        public bool AddPay(int obj_id,string accName, int itemID, int count,int type)
        {
            int num=0;
                try
                {
                    string sql = string.Empty;
                    switch (type)
                    {
                        case 1:
                            sql = string.Format("insert into linsm_info(item_obj_id,account_name,item_id,count,date,note) values({0},'{1}',{2},{3}, now(),'LinSM发送新道具')", obj_id + 1, accName, itemID, count);//赠送道具
                            break;
                        case 2:
                            sql = string.Format("insert into linsm_info(item_obj_id,account_name,item_id,count,date,note) values({0},'{1}',{2},{3}, now(),'LinSM修改道具数量')", warehouseType(itemID, accName), accName, itemID, count);//赠送道具
                            break;
                        case 3:
                            sql = string.Format("insert into linsm_info(item_obj_id,account_name,item_id,count,date,note) values({0},'{1}',{2},{3}, now(),'LinSM发送新道具给城主')", obj_id + 1, accName, itemID, count);//赠送道具
                            break;
                    }
                    
                    MySqlCommand com = new MySqlCommand(sql, DBHelper.con);
                    DBHelper.con.Open();
                    num = Convert.ToInt32(com.ExecuteNonQuery());
                }
                catch
                {
                    Error.s = "读取数据库时发生错误！";
                }
                finally
                {
                    DBHelper.con.Close();
                    DBHelper.con.Dispose();
                }
                if (num == 0)
                {
                    return false;
                }
                return true;
            }



        /// <summary>
        /// 查询道具是否存在
        /// </summary>
        /// <param name="id">道具id</param>
        /// <param name="type">道具类别</param>
        /// <returns></returns>
        public bool QuestItem(string id, int type) 
        {
            int num = 0;
            try
            {
                string sql = string.Empty;
                switch (type)
                {
                    case 1:
                        //装备
                        sql = string.Format("select * from armor where item_id={0}", id);
                        break;
                    case 2:
                        //道具
                        sql = string.Format("select * from etcitem where item_id={0}", id);
                        break;
                    case 3:
                        //武器
                        sql = string.Format("select * from weapon where item_id={0}", id);
                        break;
                }
                MySqlCommand com = new MySqlCommand(sql, DBHelper.con);
                DBHelper.con.Open();
                num = Convert.ToInt32(com.ExecuteScalar());
            }
            catch
            {
                Error.s = "读取数据库时发生错误！";
            }
            finally
            {
                DBHelper.con.Close();
                DBHelper.con.Dispose();
            }
            if (num == 0)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 查询血盟是否存在 ,目前没用到
        /// </summary>
        /// <param name="name">血盟名称</param>
        /// <returns></returns>
        public bool QuestClan(string name)
        {
            int num = 0;
            try
            {
                string sql = string.Empty;
                sql = string.Format("select * from clan_data where clan_name={0}", name);
                MySqlCommand com = new MySqlCommand(sql, DBHelper.con);
                DBHelper.con.Open();
                num = Convert.ToInt32(com.ExecuteScalar());
            }
            catch
            {
                Error.s = "读取数据库时发生错误！";
            }
            finally
            {
                DBHelper.con.Close();
                DBHelper.con.Dispose();
            }
            if (num == 0)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 获取全部血盟
        /// </summary>
        /// <returns></returns>
        public DataSet GetAllClan()
        {
            DataSet ds = new DataSet();
            try
            {
                string sql = "select a.clan_id,a.clan_name,count(b.clanid) as count from clan_data as a inner join characters as b on a.clan_id=b.clanid  group by b.clanid";
                MySqlDataAdapter objAda = new MySqlDataAdapter(sql, DBHelper.con);
                objAda.Fill(ds, "ClanTable");
            }
            catch
            {
                Error.s = "读取数据库时发生错误！";
            }
            finally
            {
                DBHelper.con.Close();
                DBHelper.con.Dispose();
            }
            return ds;
        }

        /// <summary>
        /// 查询发送的道具是否可重叠
        /// </summary>
        /// <param name="itemID">道具ID</param>
        /// <returns></returns>
        public int ItemType(int itemID)
        {
            int num = 0;
            try
            {
                string sql = string.Empty;
                sql = string.Format("select count(*) from etcitem where item_id={0} and stackable=1", itemID);
                MySqlCommand com = new MySqlCommand(sql, DBHelper.con);
                DBHelper.con.Open();
                num = Convert.ToInt32(com.ExecuteScalar());
            }
            catch
            {
                Error.s = "读取数据库时发生错误！";
            }
            finally
            {
                DBHelper.con.Close();
                DBHelper.con.Dispose();
            }
            if (num == 1)
            {
                num = 1;
            }
            else
            {
                num = 0;
            }
            return num;
        }

        /// <summary>
        /// 查询仓库中是否存在需要赠送的道具
        /// </summary>
        /// <param name="itemID"></param>
        /// <returns></returns>
        private int warehouseType(int itemID, string accID)
        {
            int num = 0;
            try
            {
                string sql = string.Empty;
                sql = string.Format("select id from character_warehouse where item_id={0} and account_name='{1}'", itemID, accID);
                MySqlCommand com = new MySqlCommand(sql, DBHelper.con);
                DBHelper.con.Open();
                num = Convert.ToInt32(com.ExecuteScalar());
            }
            catch
            {
                Error.s = "读取数据库时发生错误！";
            }
            finally
            {
                DBHelper.con.Close();
                DBHelper.con.Dispose();
            }
            return num;
        }

        private bool DeleteCastleItem(int itemID, int type)
        {
            int num = 0;
            try
            {
                string sql = string.Empty;
                switch (type)
                {
                    case 1:
                        //背包
                        sql = string.Format("delete from character_items where item_id={0}", itemID);
                        break;
                    case 2:
                        //仓库
                        sql = string.Format("delete from character_warehouse where item_id={0}", itemID);
                        break;
                    case 3:
                        //妖仓
                        sql = string.Format("delete from character_elf_warehouse where item_id={0}", itemID);
                        break;
                    case 4:
                        //盟仓
                        sql = string.Format("delete from clan_warehouse where item_id={0}", itemID);
                        break;
                }
                MySqlCommand com = new MySqlCommand(sql, DBHelper.con);
                DBHelper.con.Open();
                num = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch
            {
                Error.s = "读取数据库时发生错误！";
            }
            finally
            {
                DBHelper.con.Close();
                DBHelper.con.Dispose();
            }
            if (num == 0)
            {
                return false;
            }
            return true;
        }

        public string AdditemBYAccID(string accID, int itemID, int count)
        {
            int a = 0;//成功
            int b = 0;//失败
            int itemType = ItemType(itemID);
            int type = 1;
            int wtype = 0;
            if (warehouseType(itemID, accID) > 1)
            {
                wtype = 1;
            }
            if (itemType + wtype == 2)//道具可重叠,且仓库中有该道具
            {
                type = 2;//发送道具时只修改该道具的数量,而不是增加
            }
            string LoginID = string.Empty;

            int isok = 0;
            int id = ItemMaxId.ID();//玩家道具的流水号
            //int id = 100000000;//固定的流水号
            try
            {
                string sql = string.Empty;
                if (AddPay(id, accID, itemID, count,type))//记录成功后赠送
                {
                    switch (type)
                    {
                        case 1://插入新道具
                            sql = string.Format("insert into character_warehouse(id,account_name,item_id,item_name,count) values({0},'{1}',{2},'LinSM赠送',{3})", id + 1, accID, itemID, count);//赠送道具                            
                            break;
                        case 2://修改道具数量
                            sql = string.Format("update character_warehouse set count=count+{0} where item_id={1} and account_name='{2}' order by item_id desc Limit 1", count, itemID, accID);
                            break;
                    }
                }
                MySqlCommand com = new MySqlCommand(sql, DBHelper.con);
                DBHelper.con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch
            {
                Error.s = "读取数据库时发生错误！";
            }
            finally
            {
                DBHelper.con.Close();
                DBHelper.con.Dispose();
            }
            if (isok > 0)
            {
                a++;
                id++;
            }
            else
            {
                b++;
            }
            return "赠送成功" + a + "条\n赠送失败" + b + "条";
        }
    }
}
